<template>
  <TnNewTable
    ref="tableRef"
    :columns="columns"
    :show-no="true"
    :tn-table-props="tnTableProps"
    :query-data="queryData"
    @dataUpdate="dataLoaded"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'formType'"> {{ record.formTypeName }} </template>

      <template v-if="column.dataIndex === 'edit'">
        <!-- <a-button type="link" primary @click="handleEdit(record.formId)">设计</a-button> -->
        <MoreButton :key="Math.random()" :button-list="buttonList" :data="record" />

        <!-- <a-button type="link" primary @click="review(record)">查看</a-button>

        <a-button v-if="!disabled" type="link" primary @click="designForm(record)">设计</a-button>

        <template v-if="record.formClass !== 2">
          <a-popconfirm
            title="是否确认删除?"
            ok-text="确认"
            cancel-text="取消"
            :get-popup-container="(triggerNode):any => triggerNode.parentNode"
            @confirm="handleDel(record.formId)"
            @cancel="() => {}"
          >
            <a-button v-if="!disabled" danger type="link" class="del-button-text">删除</a-button>
          </a-popconfirm>
        </template>

        <a-button v-if="record.displayOrder !== 1 && !disabled" type="link" primary @click="orderUp(record)"
          >上移</a-button
        >

        <a-button
          v-if="record.displayOrder !== tableDataList.length && !disabled"
          type="link"
          primary
          @click="orderDown(record)"
          >下移</a-button
        > -->
      </template>
    </template>
  </TnNewTable>

  <!--表单预览-->
  <a-modal
    v-model:visible="previewVisible"
    :mask-closable="false"
    :keyboard="false"
    title="表单预览"
    width="100%"
    wrap-class-name="tn-model-full-scroll form-preview-modal"
    :footer="null"
  >
    <DynamicFormRender
      v-if="previewVisible && currRow.formId"
      :form-id="currRow.formId"
      :form-business-level="props.formBusinessLevel"
    />
  </a-modal>

  <!--表单设计-->
  <a-modal
    v-model:visible="designVisible"
    :mask-closable="false"
    :keyboard="false"
    width="100%"
    wrap-class-name="tn-model-full-scroll form-desgin-modal"
    :footer="null"
  >
    <template #title>
      表单设计
      <a-button type="primary" @click="submit">提交</a-button>
    </template>
    <AntdDesignForm
      v-if="designVisible"
      ref="refAntdDesignForm"
      :is-add="isAdd"
      :is-modal="true"
      :form-id="currRow ? currRow.formId : ''"
      :form-business-level="props.formBusinessLevel"
      :belong-business-id="props.taskId"
      @after-submit="afterSubmit()"
    />
  </a-modal>
</template>
<script lang="ts" setup name="FormList">
import { ref, reactive } from 'vue'
// formTypeOptions
import { columnsList } from './index'
import { ColumnsType } from 'ant-design-vue/lib/table'
import {
  formListApp,
  formDeleteApp,
  formBusinessList,
  formDelete,
  updateTemplateDisplayOrder,
  updateApplyDisplayOrder
} from '@@/api/form'
// import AntdDesignForm from '@@/components/formDesign/components/AntdDesignForm.vue'
// import DynamicFormRender from '@@/components/DynamicModule/DynamicFormRender/index.vue'
import { cloneDeep } from 'lodash-es'
import { Modal } from 'ant-design-vue'

interface FormatQuery {
  belongBusinessId: string | number
  formBusinessLevel: number
  formName?: string
  formType?: string | number
  projectType?: string | number
  formStatus?: string | number
}

const props = defineProps<{
  taskId: string
  sourceType: string
  formBusinessLevel: number
  disabled?: boolean
}>()

const buttonList = ref([
  {
    label: '查看',
    handler: (record) => review(record)
  },
  {
    label: '设计',
    visibleHandler: () => !props.disabled,
    handler: (record) => designForm(record)
  },
  {
    label: '删除',
    otherProps: () => ({
      danger: true
    }),
    visibleHandler: (record) => record.formClass !== 2 && !props.disabled,
    handler: (record) => {
      Modal.confirm({
        title: '是否确认删除?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => handleDel(record.formId)
      })
    }
  },
  {
    label: '上移',
    visibleHandler: (record) => record.displayOrder !== 1 && !props.disabled,
    handler: (record) => orderUp(record)
  },
  {
    label: '下移',
    visibleHandler: (record) => record.displayOrder !== tableDataList.value.length && !props.disabled,
    handler: (record) => orderDown(record)
  }
])

const columns = ref<ColumnsType>(columnsList)
const tableRef = ref()
const refAntdDesignForm = ref()
const queryData: FormatQuery = reactive({
  belongBusinessId: props.taskId,
  formBusinessLevel: props.formBusinessLevel
})
const previewVisible = ref()

const designVisible = ref()

const currRow = ref()

const submit = () => {
  // 提交表单设计
  refAntdDesignForm.value.handleSave(1)
}

const tableDataList = ref<any[]>([])
const dataLoaded = (data) => {
  tableDataList.value = data.tableData
}

// const getlabel = (val) => {
//   const currItem = formTypeOptions.find((item) => item.value === val)
//   return currItem ? currItem.label : ''
// }

const tnTableProps = {
  name: 'TaskKanbanFormConfigTable',
  asyncApi: props.sourceType === 'progressTemplate' ? formBusinessList : formListApp,
  needPagination: false
}
const reloadTable = () => {
  tableRef.value.reloadTable()
}

const handleDel = (formId) => {
  const fn = props.formBusinessLevel > 3 ? formDeleteApp : formDelete
  fn({ id: formId }).then(() => {
    reloadTable()
  })
}
const review = (row) => {
  previewVisible.value = true
  currRow.value = row
}

const isAdd = ref()

const designForm = (row) => {
  isAdd.value = false
  designVisible.value = true
  currRow.value = row
}

const afterSubmit = () => {
  designVisible.value = false
  currRow.value = {}
  reloadTable()
}

/**
 * 展示空白表单
 */
const showEmptyForm = () => {
  isAdd.value = true
  currRow.value = null
  designVisible.value = true
}

// 上移
const orderUp = (row) => {
  const temArr = cloneDeep(tableDataList.value)
  const index = temArr.findIndex((el) => el.formId === row.formId)
  ;[temArr[index - 1], temArr[index]] = [temArr[index], temArr[index - 1]]
  const params = temArr.map((item, index) => ({
    formId: item.formId,
    displayOrder: index + 1
  }))
  const fn = props.formBusinessLevel > 3 ? updateApplyDisplayOrder : updateTemplateDisplayOrder
  fn(params).then(() => {
    reloadTable()
  })
}

// 下移
const orderDown = (row) => {
  const temArr = cloneDeep(tableDataList.value)
  const index = temArr.findIndex((el) => el.formId === row.formId)
  ;[temArr[index], temArr[index + 1]] = [temArr[index + 1], temArr[index]]
  const params = temArr.map((item, index) => ({
    formId: item.formId,
    displayOrder: index + 1
  }))
  const fn = props.formBusinessLevel > 3 ? updateApplyDisplayOrder : updateTemplateDisplayOrder
  fn(params).then(() => {
    reloadTable()
  })
}

defineExpose({
  reloadTable,
  showEmptyForm
})
</script>
<style lang="less"></style>
